package com.longrise.android.byjk.plugins.dealsituation.cachecourse;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.common.DownloadConstants;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.DownloadedDetailBean;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.dealsituation.course.cache.CourseCache;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.education.insurance.InsuranceActivity;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.Constants;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoConsts;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.datasource.local.sp.CacheUtils;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.common.utils.DownLoadDetailDialog;
import com.longrise.android.byjk.utils.FileUtil;
import com.longrise.common.utils.NetUtil;
import com.longrise.common.utils.PrintLog;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.upload_offline.DBHelper;
import com.longrise.android.util.Util;
import com.longrise.filedownloader.DownloadFileInfo;
import com.longrise.filedownloader.DownloadManager;
import com.longrise.filedownloader.DownloadManager.DownloadStatus;
import com.longrise.filedownloader.DownloadService;
import com.longrise.filedownloader.OnFileDownloadStatusListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by xkj on 2016/3/14
 * 下载详情页面
 */
public class DownloadedDetailLFView extends BaseActivity implements UpdateCallBack, AdapterView.OnItemClickListener, View.OnClickListener {

    private static final String TAG = "DownloadedDetailLFView";
    public final static String COURSEID = "COURSEID";
    private static final int OPEN = 0;
    private static final int CLOSE = 1;
    public static final int START = 2;
    public static final int STOP = 3;
    public static final int NORMAL = 4; //正常模式
    public static final int DELETE = 5; //删除模式
    private static final int SWITCHBUTTON = 6;
    private static final int GETDATAFINISH = 7;
    private static final int REGETMESSAGE = 8;
    private static final int REGETMESSAGETWO = 9;
    private static final int DELAYNOTIFY = 10;
    private static final int DOWNLOADSTATUS = 11; //下载状态 单个下载
    private static final int DOWNLOADALLSTATUS = 12; //下载全部
    private static final int STUDYSTATUS = 13; //学习状态
    private int mStatus = DOWNLOADSTATUS;
    private ListView mListView;
    private DownloadedDetailAdapter mAdapter;
    private String mCourseid;
    private DBHelper dbHelper;
    private List<DownloadedDetailBean> mDownloadingList; //正在下载的列表
    private List<DownloadedDetailBean> mDownloadedList;  //已经下载完成的列表
    private List<DownloadedDetailBean> mDownloadingDeleteList; //需要删除正在下载的集合
    private List<DownloadedDetailBean> mDownloadedDeleteList; //需要删除已经下载的集合
    private List<String> mDeleteList;//需要删除的url集合
    private List<String> mStartOrStopList; //需要开始的url集合
    List<DownloadedDetailBean> mDownloadingEmptyList = new ArrayList<>();
    private RelativeLayout mRl1;
    private RelativeLayout mRl2;
    private int mListStatus = OPEN;
    private ImageView mIviconStatus;
    private int mAllDownloadStatus = STOP;
    private ImageView mIvPlay;
    private TextView mTvPlay;
    private String mCourseName;
    private int mMode = NORMAL;
    private LinearLayout mLl;
    private TextView mTvAllSelect;
    private TextView mTvDelete;
    private boolean mIsCheckAll = false; //是否已经全选
    private DownLoadDetailDialog mWaitDialog;
    private boolean isDeletee = false;
    private DownloadManager mDownloadManager;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SWITCHBUTTON:
                    switchButton();
                    break;
                case GETDATAFINISH:  //获取数据完成
                    DZZWTools.dismissDialog(null);
                    //如果正在下载和已经下载完成的都没有 则关掉当前页面
                    if (mDownloadingList.size() + mDownloadedList.size() == 0) {
                        close();
                    }
                    if (mDownloadingList.size() != 0) {
                        checkStatus(1);
                    }
                    Log.d(TAG, "mDownloadingList.size():" + mDownloadingList.size());
                    updateData();
                    break;
                case REGETMESSAGE: //下载完成 重新获取数据
                    PrintLog.d(TAG, "下载完成咯:");
                    getDataFromDB();
                    DZZWTools.dismissDialog(null);
                    break;
                case REGETMESSAGETWO: //删除完成重新 获取数据
                    isDeletee = true;
                    getDataFromDB();
                    switchMode2();
                    //DZZWTools.dismissDialog(null);
                    dismissDialog();
                    break;
            }
        }
    };

    private boolean mIsFinish = false;
    private Toolbar mToolbar;
    // private RelativeLayout mRightRliv;
    private RelativeLayout mRightRltv;
    private TextView mRighttv;

    private void getIntentData() {
        Intent intent = getIntent();
        mCourseid = intent.getStringExtra(COURSEID);
    }

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.lfview_downloadeddetail;
    }


    @Override
    public void initView() {
        Tracker_Google.getInstance().addGoogleScreenName("detail-cache-course");
        getIntentData();
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        //mRightRliv = (RelativeLayout) findViewById(R.id.bb_toolbar_right_rl);
        ImageView mRightIv = (ImageView) findViewById(R.id.iv_toolbar_share);
        mRightIv.setImageResource(R.drawable.rabish);
        mRightRltv = (RelativeLayout) findViewById(R.id.bb_toolbar_right_rl_tv);
        mRighttv = (TextView) findViewById(R.id.iv_toolbar_right_tv);
        mRighttv.setText(AppUtil.getString(R.string.downloaded_delete));
        mRightRltv.setVisibility(View.VISIBLE);
        //mRightRliv.setVisibility(View.VISIBLE);

        mListView = (ListView) findViewById(R.id.lfview_downloadeddetail_lv);
        mRl1 = (RelativeLayout) findViewById(R.id.lfview_downloadeddetail_rl1);
        mRl2 = (RelativeLayout) findViewById(R.id.lfview_downloadeddetail_rl2);
        mIviconStatus = (ImageView) findViewById(R.id.lfview_downloadeddetail_iconstatus);
        mIvPlay = (ImageView) findViewById(R.id.lfview_downloadeddetail_ivplay);
        mTvPlay = (TextView) findViewById(R.id.lfview_downloadeddetail_tvplay);


//        mTitleTv = (TextView) findViewById(R.id.lfview_downloadeddetail_tv);
//        mTitleIv = (ImageView) findViewById(R.id.lfview_downloadeddetail_iv);
//        mTitleIv.setVisibility(View.VISIBLE);
//        mRlright = (RelativeLayout) findViewById(R.id.lfview_downloadeddetail_btrl);

        mLl = (LinearLayout) findViewById(R.id.lfview_downloadeddetail_ll);
        mTvAllSelect = (TextView) findViewById(R.id.lfview_downloadeddetail_check_all); //全选
        mTvDelete = (TextView) findViewById(R.id.lfview_downloadeddetail_delete); //删除

        initData();
        regEvent(true);
    }

    private void initData() {
        dbHelper = new DBHelper(mContext);
        mDownloadManager = DownloadService.getDownloadManager();
        mAdapter = new DownloadedDetailAdapter(mContext, mDownloadManager);
        mDownloadingList = new ArrayList<>();
        mDownloadedList = new ArrayList<>();
        mDownloadingDeleteList = new ArrayList<>();
        mDownloadedDeleteList = new ArrayList<>();
        mDeleteList = new ArrayList<>();
        mStartOrStopList = new ArrayList<>();

        mAdapter.setUpdateCallback(this);
        mListView.setAdapter(mAdapter);
        getTitleFromDb();
        getDataFromDB();
        mIsFinish = false;

    }

    /**
     * 更新数据刷新页面
     */
    private void updateData() {

//        CourseOfflineCacheUtils.removeUserVideoParTitle(mCourseid);
//        CourseOfflineCacheUtils.removeCachedUserVideoParTitle(mCourseid);
//        CourseOfflineCacheUtils.removeUserVideoLList(mCourseid);
//        CourseOfflineCacheUtils.removeCachedUserVideoLList(mCourseid);
//
        if (mListStatus == OPEN) {
            mIviconStatus.setImageResource(R.drawable.icon_up);
            mAdapter.setData(mDownloadingList, mDownloadedList, mMode, mCourseid, mStudentNo);
            if (mDownloadingList.size() == 0) {
                mRl1.setVisibility(View.GONE);
                mRl2.setVisibility(View.GONE);
            } else {
                if (mMode == NORMAL) {
                    mRl2.setVisibility(View.VISIBLE);
                    mRl1.setVisibility(View.VISIBLE);
                } else {
                    mRl2.setVisibility(View.GONE);
                    mRl1.setVisibility(View.VISIBLE);
                }
            }
        } else {
            mIviconStatus.setImageResource(R.drawable.icon_down);
            mRl2.setVisibility(View.GONE);
            mAdapter.setData(mDownloadingEmptyList, mDownloadedList, mMode, mCourseid, mStudentNo);
            if (mDownloadingList.size() == 0) {
                mRl1.setVisibility(View.GONE);
                mRl2.setVisibility(View.GONE);
            } else {
                mRl2.setVisibility(View.GONE);
                mRl1.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 从数据库中拿取课程名称
     */
    private String mStudentNo = "";

    private void getTitleFromDb() {
        Disposable courseNameds = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                SQLiteDatabase db = null;
                Cursor cursor = null;
                String courseName = null;
                try {
                    db = dbHelper.getWritableDatabase();
                    cursor = db.rawQuery("select courseName,studentno from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL + " where userID = ? and courseID = ? ", new String[]{UserInfor.getInstance().getUserid(), mCourseid});
                    if (cursor.moveToNext()) {
                        courseName = cursor.getString(cursor.getColumnIndex("courseName"));
                        mStudentNo = cursor.getString(cursor.getColumnIndex(DownloadConstants.STUDENTNO));

                        //课后习题需要 暂做处理 ExercisesActivity
                        CacheUtils.setString(Constants.CourseTest.INTENT_PNAME, courseName);
                    }
                } catch (Exception ee) {
                    ee.printStackTrace();

                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                    if (db != null) {
                        db.close();
                    }
                }
                e.onNext(courseName);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                mToolbar.setTitle(s);
                //sjz
                CacheUtils.setString(Constants.CourseTest.INTENT_PNAME, s);
                Tracker_Google.getInstance().addGoogleScreenName("下载详情:" + s);
            }
        });
        mRxmanager.addDisposable(courseNameds);
    }

    private void getDataFromDB() {
        DZZWTools.showWaitDialog(mContext);
        new Thread() {
            @Override
            public void run() {
                SQLiteDatabase db = null;
                Cursor cursor = null;
                mDownloadingList.clear();
                mDownloadedList.clear();

                Message msg = handler.obtainMessage();
                msg.what = SWITCHBUTTON;
                handler.sendMessage(msg);

                try {
                    db = dbHelper.getWritableDatabase();

                    cursor = db.rawQuery("select * from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL + " where userID = ? and courseID = ? order by position asc ", new String[]{UserInfor.getInstance().getUserid(), mCourseid});
                    while (cursor.moveToNext()) {
                        mCourseName = cursor.getString(cursor.getColumnIndex("courseName"));
                        String downloadurl = cursor.getString(cursor.getColumnIndex("downloadurl"));
                        String partpath = cursor.getString(cursor.getColumnIndex("partpath"));
                        String chapterName = cursor.getString(cursor.getColumnIndex("chapterName"));
                        String cwName = cursor.getString(cursor.getColumnIndex("cwName"));
                        String cwId = cursor.getString(cursor.getColumnIndex("cwID"));
                        String cachepath = cursor.getString(cursor.getColumnIndex("cachepath"));
                        String chapterid = cursor.getString(cursor.getColumnIndex("chapterid"));
                        int videopass = cursor.getInt(cursor.getColumnIndex("videopass"));
                        int hasqa = cursor.getInt(cursor.getColumnIndex("hasqa"));
                        int isfinished = cursor.getInt(cursor.getColumnIndex("isfinished"));
                        int position = cursor.getInt(cursor.getColumnIndex("position"));
                        String pathno = cursor.getString(cursor.getColumnIndex("pathno"));

                        DownloadedDetailBean bean = new DownloadedDetailBean();
                        bean.setPathnojd(pathno);
                        bean.setPosition(position);
                        bean.setUrl(downloadurl);
                        bean.setPartPath(partpath);
                        bean.setChapterName(chapterName);
                        bean.setCwName(cwName);
                        bean.setCachepath(cachepath);
                        if (videopass == 0) {
                            bean.setVideopass(false);
                        } else {
                            bean.setVideopass(true);
                        }
                        if (hasqa == 0) {
                            bean.setHasqa(false);
                        } else {
                            bean.setHasqa(true);
                        }
                        if (isfinished == 0) {
                            bean.setIsfinish(false);
                        } else {
                            bean.setIsfinish(true);
                        }

                        long totalLength = 0;
                        mDownloadManager.getFileSize(downloadurl);
                        bean.setTotalLength(totalLength);
                        bean.setCwId(cwId);
                        bean.setChapterId(chapterid);

                        boolean hasDownloaded = FileUtil.isHasDownloaded(mContext, UserInfor.getInstance().getUserid(), cwId);
                        PrintLog.d(TAG, "cwId" + cwId);
                        PrintLog.d(TAG, "hasDownloaded" + hasDownloaded);
                        if (hasDownloaded) {
                            bean.setStatus(DownloadedDetailBean.FINISH);
                            mDownloadedList.add(bean);
                        } else {
                            mDownloadingList.add(bean);
                        }
                    }
                    addAndInitTask(mDownloadingList);
                } catch (Exception e) {
                    PrintLog.d(TAG, "exception:" + e.toString());
                } finally {
                    if (db != null) {
                        db.close();
                    }
                    if (cursor != null) {
                        cursor.close();
                    }
                    Message msg1 = handler.obtainMessage();
                    msg1.what = GETDATAFINISH;
                    handler.sendMessage(msg1);
                }
            }
        }.start();
    }

    /**
     * 如果因版本升级未将url添加进filedownloader的 现在添加
     */
    private void addAndInitTask(List<DownloadedDetailBean> list) {
        for (DownloadedDetailBean bean : list) {
            String url = bean.getUrl();
            String cachepath = bean.getCachepath();
            mDownloadManager.addAndInitTask(url, cachepath);
        }
    }

    private void regEvent(boolean b) {
        if (mListView != null) {
            mListView.setOnItemClickListener(b ? this : null);
        }
        if (mRl1 != null) {
            mRl1.setOnClickListener(b ? this : null);
        }
        if (mRl2 != null) {
            mRl2.setOnClickListener(b ? this : null);
        }
        if (mTvAllSelect != null) {
            mTvAllSelect.setOnClickListener(b ? this : null);
        }
        if (mTvDelete != null) {
            mTvDelete.setOnClickListener(b ? this : null);
        }
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                close();
            }
        });
        // mRightRliv.setOnClickListener(this);
        mRightRltv.setOnClickListener(this);
    }

    /**
     * 检查状态 判断当前是全部开始状态还是全部暂停状态
     */
    public void checkStatus(int flag) {
        int mstatus = START;
        for (DownloadedDetailBean bean : mDownloadingList) {
            String url = bean.getUrl();
            DownloadStatus status = mDownloadManager.getStatus(url);
            PrintLog.d(TAG, "STATUS:" + url + "::" + status);
            if (status == DownloadStatus.STOP || status == DownloadStatus.FAIL) {
                mstatus = STOP;
                break;
            }
        }
        if (flag == 1) {
            show(mstatus);
        } else if (flag == 2 && mstatus == START) {
            show(mstatus);
        }

    }

    @Override
    public void startProgress(String url, final int position) {

        mDownloadManager.setOnFileDownloadStatusListener(url, new OnFileDownloadStatusListener() {
            @Override
            public void onFileDownloadStatusWaiting(DownloadFileInfo downloadFileInfo) {
                updateProgressPartly(1, downloadFileInfo, position);
            }

            @Override
            public void onFileDownloadStatusDownloading(DownloadFileInfo downloadFileInfo) {
                updateProgressPartly(2, downloadFileInfo, position);
            }

            @Override
            public void onFileDownloadStatusPaused(DownloadFileInfo downloadFileInfo) {
                updateProgressPartly(3, downloadFileInfo, position);
            }

            @Override
            public void onFileDownloadStatusCompleted(DownloadFileInfo downloadFileInfo) {
                updateProgressPartly(4, downloadFileInfo, position);
            }

            @Override
            public void onFileDownloadStatusFailed(DownloadFileInfo downloadFileInfo) {
                updateProgressPartly(5, downloadFileInfo, position);
            }
        });
    }

    /**
     * 下载完成后刷新界面
     */
    private synchronized void toRefresh(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        for (int i = 0; i < mDownloadingList.size(); i++) {
            DownloadedDetailBean downloadedDetailBean = mDownloadingList.get(i);
            String beanurl = downloadedDetailBean.getUrl();
            int position = downloadedDetailBean.getPosition();
            if (url.equals(beanurl)) {
                mDownloadingList.remove(downloadedDetailBean);
                int po = 0;
                for (int j = 0; j < mDownloadedList.size(); j++) {
                    DownloadedDetailBean downloadedDetailBean1 = mDownloadedList.get(j);
                    int position1 = downloadedDetailBean1.getPosition();
                    if (position1 > position) {
                        break;
                    } else {
                        po++;
                    }
                }
                mDownloadedList.add(po, downloadedDetailBean);
                updateData();
                break;
            }
        }
    }

    private void updateProgressPartly(int mark, DownloadFileInfo downloadFileInfo, int position) {
        int firstVisiblePosition = mListView.getFirstVisiblePosition();
        int lastVisiblePosition = mListView.getLastVisiblePosition();
        if (position >= firstVisiblePosition && position <= lastVisiblePosition) {
            View view = mListView.getChildAt(position - firstVisiblePosition);
            if (view.getTag() instanceof DownloadedDetailAdapter.Holder) {
                DownloadedDetailAdapter.Holder viewHolder = (DownloadedDetailAdapter.Holder) view.getTag();
                long downloadSize = downloadFileInfo.getDownloadSize();
                long fileSize = downloadFileInfo.getFileSize();
                int progress = downloadFileInfo.getProgress();
                String url = downloadFileInfo.getUrl();
                String fileDownloadedSize = FileUtil.FormetFileSize(downloadSize);
                String fileSize2 = FileUtil.FormetFileSize(fileSize);

                viewHolder.mPb.setProgress(progress);
                if (fileSize == 0) {
                    viewHolder.mTvpb.setText("0.00M/0.00M");
                } else {
                    viewHolder.mTvpb.setText(fileDownloadedSize + "/" + fileSize2);
                }
                PrintLog.d(TAG, "mark:" + mark);
                switch (mark) {
                    case 1:
                        viewHolder.mTvstatus2.setText("等待中");
                        checkStatus(2);
                        break;
                    case 2:
                        viewHolder.mTvstatus2.setText("下载中");
                        checkStatus(2);
                        break;
                    case 3:
                        viewHolder.mTvstatus2.setText("已暂停");
                        show(STOP);
                        break;
                    case 4: //下载成功
                        toRefresh(url);
                        break;
                    case 5: //下载失败
                        viewHolder.mTvstatus2.setText("已暂停");
                        show(STOP);
                        break;
                }
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mMode == DELETE) { //删除的状态
            DownloadedDetailBean downloadedDetailBean = null;

            if (mListStatus == DownloadedDetailLFView.OPEN) {  //展开状态
                if (position < mDownloadingList.size()) {
                    downloadedDetailBean = mDownloadingList.get(position);
                    if (downloadedDetailBean.isChecked()) {
                        downloadedDetailBean.setIsChecked(false);
                        mDownloadingDeleteList.remove(downloadedDetailBean);
                    } else {
                        downloadedDetailBean.setIsChecked(true);
                        mDownloadingDeleteList.add(downloadedDetailBean);
                    }
                } else if (position > mDownloadingList.size()) {
                    downloadedDetailBean = mDownloadedList.get(position - mDownloadingList.size() - 1);
                    if (downloadedDetailBean.isChecked()) {
                        downloadedDetailBean.setIsChecked(false);
                        mDownloadedDeleteList.remove(downloadedDetailBean);
                    } else {
                        downloadedDetailBean.setIsChecked(true);
                        mDownloadedDeleteList.add(downloadedDetailBean);
                    }
                }

            } else if (mListStatus == DownloadedDetailLFView.CLOSE && position > 0) { //正在下载item合并状态
                downloadedDetailBean = mDownloadedList.get(position - 1);
                if (downloadedDetailBean.isChecked()) {
                    downloadedDetailBean.setIsChecked(false);
                    mDownloadedDeleteList.remove(downloadedDetailBean);
                } else {
                    downloadedDetailBean.setIsChecked(true);
                    mDownloadedDeleteList.add(downloadedDetailBean);
                }
            }


            if (downloadedDetailBean != null) {

                switchButton();
                updateData();

            }

        } else {
            if (mListStatus == DownloadedDetailLFView.OPEN) {  //展开状态
                if (position < mDownloadingList.size()) {
                    DownloadedDetailBean downloadedDetailBean = mDownloadingList.get(position);
                    String url = downloadedDetailBean.getUrl();
                    if (TextUtils.isEmpty(url)) {
                        return;
                    }
                    // judgeNetwork(position);
                    mStatus = DOWNLOADSTATUS;
                    isAbleStudy(null, position);

                } else if (position > mDownloadingList.size()) {  //已经下载完成的item
                    DownloadedDetailBean downloadedDetailBean = mDownloadedList.get(position - mDownloadingList.size() - 1);
                    mStatus = STUDYSTATUS;
                    isAbleStudy(downloadedDetailBean, 0);
                }
            } else {
                if (position > 0) {
                    DownloadedDetailBean downloadedDetailBean = mDownloadedList.get(position - 1);
                    mStatus = STUDYSTATUS;
                    isAbleStudy(downloadedDetailBean, 0);
                }
            }
        }
    }

    /**
     * 开始所选下载的项目
     *
     * @param position item在集合中的位置
     */
    private void startItem(int position) {
        DownloadedDetailBean downloadedDetailBean = mDownloadingList.get(position);
        String url = downloadedDetailBean.getUrl();
        String partPath = downloadedDetailBean.getPartPath();
        //       startProgress(url, partPath, position);
        //       downloadedDetailBean.setStatus(DownloadedDetailBean.DOWNLOADING);
        boolean b = mDownloadManager.switchStatus(url);
        if (!b) {
            String cachepath = downloadedDetailBean.getCachepath();
            mDownloadManager.addTask(url, cachepath);
        }
    }

    private void judgeNetwork(final int position) {
        //判断有没有网络
        if (!NetUtil.checkNetEnable()) {
            return;
        }

        DownloadedDetailBean downloadedDetailBean = mDownloadingList.get(position);
        String url = downloadedDetailBean.getUrl();
        DownloadStatus status = mDownloadManager.getStatus(url);
        if (DownloadStatus.DOWNLOADING.equals(status)) { //正在下载的点击直接暂停不用判断是否是移动网络
            startItem(position);
        } else {
            boolean canMobileDownload = Control.isCanMobileDownload();
            //判断当前网络是否是移动网络
            if (!canMobileDownload && NetUtil.isDataNet(mContext)) {
                View v = View.inflate(mContext, R.layout.dialog_exit, null);
                TextView cacnle_3g = (TextView) v.findViewById(R.id.text_cancle);
                TextView confrim_3g = (TextView) v.findViewById(R.id.text_confirm);
                TextView title = (TextView) v.findViewById(R.id.dialog_hint);
                TextView msg = (TextView) v.findViewById(R.id.text_m);
                title.setText("提示");
                msg.setText("您当前处于非wifi网络环境下，继续使用可能产生流量");
                cacnle_3g.setOnClickListener(this);
                confrim_3g.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogUtil.getInstance().dismiss();
                        startItem(position);
                    }
                });
                DialogUtil.getInstance().creatAlertDialog(mContext, v, 266, 159);
            } else {
                startItem(position);
            }
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lfview_downloadeddetail_rl1:
                switchListState();
                break;
            case R.id.lfview_downloadeddetail_rl2:
                stopOrStart();
                break;
            case R.id.bb_toolbar_right_rl:  //垃圾桶图标
            case R.id.bb_toolbar_right_rl_tv:
                switchMode();
                break;
            case R.id.lfview_downloadeddetail_check_all: //全选
                toSelectAll();
                break;
            case R.id.lfview_downloadeddetail_delete: //删除
                toShowDeleteDialog();
                break;
            case R.id.dialog_clearcw_cancle: //删除dialog取消
                DialogUtil.getInstance().dismiss();
                break;
            case R.id.dialog_clearcw_confirm: //删除dialog确认
                DialogUtil.getInstance().dismiss();
                // DZZWTools.showWaitDialog(mContext);
                showWaitDialog(mContext);
                new Thread() {
                    @Override
                    public void run() {
                        toDelete();
                    }
                }.start();
                break;
            case R.id.text_cancle:   //取消在移动网络下下载
                DialogUtil.getInstance().dismiss();
                break;
        }
    }

    /**
     * 弹出是否删除的dialog
     */
    private void toShowDeleteDialog() {
        View view = View.inflate(mContext, R.layout.dialog_clearcw, null);
        TextView text_Cancle = (TextView) view.findViewById(R.id.dialog_clearcw_cancle);
        TextView text_Confirm = (TextView) view.findViewById(R.id.dialog_clearcw_confirm);
        TextView text_msg = (TextView) view.findViewById(R.id.dialog_clearcw_message);
        String msg = "确定要删除该" + (mDownloadingDeleteList.size() + mDownloadedDeleteList.size()) + "项吗?\n同时也会删除本地文件。";
        text_msg.setText(msg);
        text_Cancle.setOnClickListener(this);
        text_Confirm.setOnClickListener(this);
        DialogUtil.getInstance().creatAlertDialog(mContext, view, 266, 171);
    }

    /**
     * 全选与取消全选
     */
    private void toSelectAll() {
        mDownloadedDeleteList.clear();
        mDownloadingDeleteList.clear();
        if (mIsCheckAll) { //取消全选
            for (int i = 0; i < mDownloadingList.size(); i++) {
                DownloadedDetailBean downloadedDetailBean = mDownloadingList.get(i);
                downloadedDetailBean.setIsChecked(false);
            }
            for (int j = 0; j < mDownloadedList.size(); j++) {
                DownloadedDetailBean downloadedDetailBean = mDownloadedList.get(j);
                downloadedDetailBean.setIsChecked(false);
            }
        } else { //全选
            mDownloadedDeleteList.addAll(mDownloadedList);
            mDownloadingDeleteList.addAll(mDownloadingList);
            for (int x = 0; x < mDownloadingList.size(); x++) {
                DownloadedDetailBean downloadedDetailBean = mDownloadingList.get(x);
                downloadedDetailBean.setIsChecked(true);
            }
            for (int y = 0; y < mDownloadedList.size(); y++) {
                DownloadedDetailBean downloadedDetailBean = mDownloadedList.get(y);
                downloadedDetailBean.setIsChecked(true);
            }
        }
        updateData();
        switchButton();
    }

    /**
     * 底部两个button的状态改变
     */
    public void switchButton() {
        if (mDownloadedDeleteList.size() + mDownloadingDeleteList.size() == 0) { //未选择删除item
            mTvDelete.setText("删除");
            mTvDelete.setBackgroundColor(Color.parseColor("#A0A0A0"));
            mTvDelete.setClickable(false);
            mTvAllSelect.setText("全选");
            mIsCheckAll = false;
        } else {
            mTvDelete.setText("删除(" + (mDownloadingDeleteList.size() + mDownloadedDeleteList.size()) + ")");
            mTvDelete.setBackgroundResource(R.drawable.selecter_bt_cache_start);
            mTvDelete.setClickable(true);
            if (mDownloadingDeleteList.size() + mDownloadedDeleteList.size() == mDownloadedList.size() + mDownloadingList.size()) {
                mTvAllSelect.setText("取消全选");
                mIsCheckAll = true;
            } else {
                mTvAllSelect.setText("全选");
                mIsCheckAll = false;
            }
        }

    }

    /**
     * 删除后更改状态
     */
    public void switchMode2() {
        for (int i = 0; i < mDownloadingDeleteList.size(); i++) {
            DownloadedDetailBean downloadedDetailBean = mDownloadingDeleteList.get(i);
            downloadedDetailBean.setIsChecked(false);
        }
        for (int j = 0; j < mDownloadedDeleteList.size(); j++) {
            DownloadedDetailBean downloadedDetailBean = mDownloadedDeleteList.get(j);
            downloadedDetailBean.setIsChecked(false);
        }
        mDownloadedDeleteList.clear();
        mDownloadingDeleteList.clear();

        mMode = NORMAL;
        mLl.setVisibility(View.GONE);

        // mRightRliv.setVisibility(View.VISIBLE);
        //mRightRltv.setVisibility(View.GONE);
        mRighttv.setText(AppUtil.getString(R.string.downloaded_delete));

//        mTitleIv.setVisibility(View.VISIBLE);
//        mTitleTv.setVisibility(View.INVISIBLE);

    }

    /**
     * 点击垃圾桶图标后 正常和删除的两种状态选择
     */
    public void switchMode() {
        for (int i = 0; i < mDownloadingDeleteList.size(); i++) {
            DownloadedDetailBean downloadedDetailBean = mDownloadingDeleteList.get(i);
            downloadedDetailBean.setIsChecked(false);
        }
        for (int j = 0; j < mDownloadedDeleteList.size(); j++) {
            DownloadedDetailBean downloadedDetailBean = mDownloadedDeleteList.get(j);
            downloadedDetailBean.setIsChecked(false);
        }
        mDownloadedDeleteList.clear();
        mDownloadingDeleteList.clear();
        if (mMode == NORMAL) {
            mMode = DELETE;
            mLl.setVisibility(View.VISIBLE);
            // mRightRliv.setVisibility(View.GONE);
            // mRightRltv.setVisibility(View.VISIBLE);
            mRighttv.setText(AppUtil.getString(R.string.downloaded_cancel));

//            mTitleIv.setVisibility(View.INVISIBLE);
//            mTitleTv.setVisibility(View.VISIBLE);
        } else {
            mMode = NORMAL;
            mLl.setVisibility(View.GONE);
            // mRightRliv.setVisibility(View.VISIBLE);
            //  mRightRltv.setVisibility(View.GONE);
            mRighttv.setText(AppUtil.getString(R.string.downloaded_delete));

//            mTitleIv.setVisibility(View.VISIBLE);
//            mTitleTv.setVisibility(View.INVISIBLE);
        }
        updateData();
        switchButton();
    }

    /**
     * 控制正在缓存是否展开
     */
    private void switchListState() {
        //当前是展开的状态
        if (mListStatus == DownloadedDetailLFView.OPEN) {
            mListStatus = DownloadedDetailLFView.CLOSE;
            updateData();
        } else {
            mListStatus = DownloadedDetailLFView.OPEN;
            updateData();
        }
    }

    /**
     * 未下载完成的item 全部开始下载 或者全部暂停
     */
    private void stopOrStart() {
        if (mAllDownloadStatus == DownloadedDetailLFView.START) {
            mStartOrStopList.clear();
            for (int x = 0; x < mDownloadingList.size(); x++) {
                //  stopItem(x);
                DownloadedDetailBean downloadedDetailBean = mDownloadingList.get(x);
                String url = downloadedDetailBean.getUrl();
                mStartOrStopList.add(url);
            }
            mAllDownloadStatus = DownloadedDetailLFView.STOP;
            mIvPlay.setImageResource(R.drawable.start);
            mTvPlay.setText("全部开始");
            mDownloadManager.stopAll(mStartOrStopList);
        } else {
            mStatus = DOWNLOADALLSTATUS;
            isAbleStudy(null, 0);
        }
    }

    /**
     * 全部开始
     */
    private void toStartAll() {
        mStartOrStopList.clear();
        for (int y = 0; y < mDownloadingList.size(); y++) {
            //startItem(y);
            DownloadedDetailBean downloadedDetailBean = mDownloadingList.get(y);
            String url = downloadedDetailBean.getUrl();
            mStartOrStopList.add(url);
        }
        mAllDownloadStatus = DownloadedDetailLFView.START;
        mIvPlay.setImageResource(R.drawable.stop);
        mTvPlay.setText("全部暂停");
        mDownloadManager.startAll(mStartOrStopList);
    }

    /**
     * 切换全部开始或者全部暂停状态
     *
     * @param status 状态值
     */
    public void show(int status) {
        if (status == START) {
            mAllDownloadStatus = DownloadedDetailLFView.START;
            mIvPlay.setImageResource(R.drawable.stop);
            mTvPlay.setText("全部暂停");
        } else if (status == STOP) {
            mAllDownloadStatus = DownloadedDetailLFView.STOP;
            mIvPlay.setImageResource(R.drawable.start);
            mTvPlay.setText("全部开始");
        }
    }

    /**
     * 删除课件
     */
    private void toDelete() {
        mDeleteList.clear();
        for (int i = 0; i < mDownloadingDeleteList.size(); i++) {
            DownloadedDetailBean downloadedDetailBean = mDownloadingDeleteList.get(i);
            toDelete(downloadedDetailBean);
            String url = downloadedDetailBean.getUrl();
            mDeleteList.add(url);
        }
        for (int j = 0; j < mDownloadedDeleteList.size(); j++) {
            DownloadedDetailBean downloadedDetailBean = mDownloadedDeleteList.get(j);
            toDelete(downloadedDetailBean);
            String url = downloadedDetailBean.getUrl();
            mDeleteList.add(url);
        }
        mDownloadManager.deleteMultiTasks(mDeleteList);
        mDownloadingDeleteList.clear();
        mDownloadedDeleteList.clear();
        Message msg = handler.obtainMessage();
        msg.what = REGETMESSAGETWO;
        handler.sendMessageDelayed(msg, 500);
    }

    /**
     * 删除某一个课件
     *
     * @param downloadedDetailBean 课件bean
     */
    private void toDelete(DownloadedDetailBean downloadedDetailBean) {
        String cwId = downloadedDetailBean.getCwId();
        toDeletDB(cwId);
    }

    /**
     * 删除
     */
    private void toDeletDB(String cwId) {
        SQLiteDatabase db = null;
        try {
            db = dbHelper.getWritableDatabase();
            int delete = db.delete(DownloadConstants.TBNAME_DOWNLOAD_DETAIL, "userID = ? and courseID = ? and cwID = ?", new String[]{UserInfor.getInstance().getUserid(), mCourseid, cwId});
            PrintLog.d(TAG, "delete:" + cwId + "::" + delete);
        } catch (Exception e) {
            PrintLog.d(TAG, "EXCEPTION2:" + e.toString());
        } finally {
            db.close();
        }
    }

    /**
     * 检查是否能够播放 sjz  废弃 2017-08-16
     */
    private void toPlay(final DownloadedDetailBean downloadedDetailBean) {
        DZZWTools.showWaitDialog(mContext);
        EntityBean bean = new EntityBean();
        bean.set("rediskey_prefix", UserInfor.getInstance().getUserid());
        bean.set("rediskey_suffix", "playauthority");
        bean.set("redisvalue", Util.getLocalMacAddress(mContext));
        EntityBean serBean = new EntityBean();
        serBean.set("bean", bean);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_course_checkVideoPlayingAuthorityLock", serBean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                if (result != null) {
                    EntityBean resultBean = (EntityBean) result;
                    if (resultBean.getInt("resultstate") == 1) {
                        EntityBean resultState = resultBean.getBean("result");
                        int state = resultState.getInt("playingstate");
                        if (state == 1) {
                            openMedia(downloadedDetailBean);

                        } else {
                            DZZWTools.showToast(mContext, mContext.getString(R.string.no_power_video), Toast.LENGTH_SHORT);
                        }
                    }
                } else {
                    DZZWTools.showToast(mContext, mContext.getString(R.string.networkerror), Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                DZZWTools.showToast(mContext, mContext.getString(R.string.networkerror), Toast.LENGTH_SHORT);
            }

            @Override
            public void onFinished(String key, String service) {
                DZZWTools.dismissDialog(null);
            }
        });
    }

    /**
     * 打开播放器  sjz
     */
    private void openMedia(DownloadedDetailBean downloadedDetailBean) {
        if (!NetUtil.checkNetEnable()) {
            return;
        }
        if (downloadedDetailBean != null) {
            String cwId = downloadedDetailBean.getCwId();
            String cachepath = downloadedDetailBean.getCachepath();
            String videoTitle = downloadedDetailBean.getCwName();
            String pathNo = downloadedDetailBean.getPathnojd();
            File file = new File(cachepath);

            if (!file.exists()) {
                cachepath = toGetNewPath(UserInfor.getInstance().getUserid(), cwId);
                if (TextUtils.isEmpty(cachepath)) {
                    DZZWTools.showToast(mContext, "您缓存的课程不存在,请删除后重新缓存", 0);
                    return;
                }
            }

//            boolean realCourse = mDownloadManager.isRealCourse(cachepath, downloadedDetailBean.getUrl());

            VideoParams videoParams = new VideoParams();
            videoParams.mCourseId = mCourseid;
            videoParams.mStudentNo = mStudentNo;
            videoParams.mPathNo = pathNo;
            videoParams.mCwid = cwId;
            videoParams.mCwidName = videoTitle;
            videoParams.mFinish = downloadedDetailBean.isfinish();
            videoParams.mHasqa = downloadedDetailBean.isHasqa();
            videoParams.mVideopass = downloadedDetailBean.isVideopass();
            videoParams.mCwidLocal = null;

            Intent intent = new Intent(mContext, InsuranceActivity.class);//BBVideoActivity.class
            intent.putExtra(VideoConsts.VIDEO_PARAMS_PARCELABLE, videoParams);
            mContext.startActivity(intent);
        }
    }

    /**
     * 检查视频是否能够学习 sjz
     * 逻辑说明：先检查该视频过是否能够学习（是否已经过期），然后check该视频是否有播放权限
     */
    private void isAbleStudy(final DownloadedDetailBean downloadedDetailBean, final int position) {
        DZZWTools.showWaitDialog(mContext);
        UserInfor userInfor = UserInfor.getInstance();
        EntityBean coursEntityBean = new EntityBean();
        coursEntityBean.set("cardno", userInfor.getUsersfzh());
        coursEntityBean.set("courseid", mCourseid);
        EntityBean argBean = new EntityBean();
        argBean.set("bean", coursEntityBean);
        DZZWTools.showWaitDialog(mContext);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_course_sTrainResDirStructBean", argBean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                if (mIsFinish) return;
                EntityBean res_ = (EntityBean) result;
                if (res_ != null) {
                    if (res_.getInt("resultstate") == 1) {
                        EntityBean parseResult = res_.getBean("result");
                        //是否已经开通
                        boolean issinguptrain = parseResult.getBoolean("issinguptrain");
                        //是否能够学习
                        boolean isablestudy = parseResult.getBoolean("isablestudy");
                        //是否关闭
                        boolean isclose = parseResult.getBoolean("isclose");
                        //是否已经关闭
                        boolean isablesignup = parseResult.getBoolean("isablesignup");
                        //是否可以延期
                        boolean isabledelaycourse = parseResult.getBoolean("isabledelaycourse");
                        EntityBean traindirstruct = parseResult.getBean("traindirstruct");
                        boolean ispass = traindirstruct.getBoolean("ispass", false);

                        if (isclose) {
                            //已下架
                            DZZWTools.showToast(mContext, mContext.getString(R.string.download_course_yxj), Toast.LENGTH_SHORT);
                        } else {//不可以学习
                            if (!isablestudy) {
                                if (issinguptrain && !isabledelaycourse && !isablesignup) { //购买过，不可以延期， 不可以报名 已关闭状态
                                    if (ispass) {  //已过期
                                        DZZWTools.showToast(mContext, mContext.getString(R.string.course_state_is_gq), Toast.LENGTH_SHORT);
                                    } else {       //已关闭
                                        DZZWTools.showToast(mContext, mContext.getString(R.string.download_course_ygb_), Toast.LENGTH_SHORT);
                                    }
                                } else {
                                    DZZWTools.showToast(mContext, mContext.getString(R.string.course_state_is_gq), Toast.LENGTH_SHORT);
                                }
                            } else {
                                if (mStatus == DOWNLOADSTATUS) {
                                    judgeNetwork(position);
                                } else if (mStatus == STUDYSTATUS) {
//                                    toPlay(downloadedDetailBean);
                                    openMedia(downloadedDetailBean);
                                } else if (mStatus == DOWNLOADALLSTATUS) {
                                    toStartAll();
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                DZZWTools.showToast(mContext, mContext.getString(R.string.networkerror), Toast.LENGTH_SHORT);
            }

            @Override
            public void onFinished(String key, String service) {
                DZZWTools.dismissDialog(null); //不能在finished中调用   sjz
            }
        });

    }


    /**
     * 同一个视频不会缓存两遍
     */
    public String toGetNewPath(String userId, String cwId) {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = dbHelper.getWritableDatabase();
            cursor = db.rawQuery("select * from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL + " where userID = ? and cwID = ? ", new String[]{userId, cwId});
            if (cursor.moveToNext()) {
                String cachepath = cursor.getString(cursor.getColumnIndex("cachepath"));

                //判读文件是否存在
                File file = new File(cachepath);
                if (file.exists()) {
                    return cachepath;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (db != null) {
                db.close();
            }
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    /**
     * 显示dialog
     *
     * @param cxt
     */
    private void showWaitDialog(Context cxt) {
        try {
            if (mWaitDialog == null) {
                synchronized (DZZWTools.class) {
                    if (mWaitDialog == null) {
                        mWaitDialog = new DownLoadDetailDialog(cxt);
                    }
                }
            }
            if (!mWaitDialog.isShowing()) {
                mWaitDialog.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 如果未用到PullToReFresh则传递null
     */
    private void dismissDialog() {
        if (mWaitDialog != null) {
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }

    /**
     * 关闭当前页
     */
    private void close() {
        mIsFinish = true;
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mAdapter != null) {
            mAdapter.shutdownCacheTask();
        }

        CourseCache.setCacheFlag(CourseCache.Flag.FLAG_FROM_COURSE_DETAIL);

    }
}
